<!--
  管理员登录页面
  注意：此页面已迁移到新的分离式登录系统
  新的登录入口：/auth (选择页面) -> /auth/admin-login (管理员登录)
-->
<template>
  <div class="admin-login-container">
    <div class="admin-login-form-wrapper">
      <div class="admin-login-header">
        <div class="logo">方舟鞋城 - 管理后台</div>
        <h2>管理员登录</h2>
        <p class="subtitle">请输入管理员账号信息</p>
      </div>

      <el-form
        ref="adminLoginFormRef"
        :model="adminLoginForm"
        :rules="adminLoginRules"
        class="admin-login-form"
        @submit.prevent="handleAdminLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="adminLoginForm.username"
            placeholder="管理员用户名"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="adminLoginForm.password"
            type="password"
            placeholder="管理员密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleAdminLogin"
          />
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="adminLoginForm.rememberMe">记住我</el-checkbox>
          <router-link to="/auth/login" class="user-login-link">普通用户登录</router-link>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="authStore.isLoading"
            class="admin-login-button"
            @click="handleAdminLogin"
          >
            {{ authStore.isLoading ? '登录中...' : '管理员登录' }}
          </el-button>
        </el-form-item>

        <!-- 已弃用：开发模式管理员快速登录 -->
        <!-- <div v-if="isDev" class="dev-helper">
          <el-alert
            title="开发模式：管理员账号 (admin / admin123)"
            type="info"
            :closable="false"
          />
          <el-button size="small" type="warning" @click="fillAdminAndLogin">一键管理员登录</el-button>
        </div> -->

        <div class="back-to-user">
          <el-button type="text" @click="goToUserLogin">
            <el-icon><ArrowLeft /></el-icon>
            返回普通用户登录
          </el-button>
        </div>
      </el-form>
    </div>

    <div class="admin-login-image" v-if="!isMobile">
      <div class="admin-login-bg"></div>
    </div>

    <!-- 错误提示 -->
    <el-dialog v-model="errorDialogVisible" title="登录失败" width="400px" center>
      <p>{{ authStore.error }}</p>
      <template #footer>
        <el-button type="primary" @click="errorDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { authService } from '@/api/authService'
import { extractErrorMessage } from '@/utils/errorHandler'

const router = useRouter()
const authStore = useAuthStore()

const adminLoginFormRef = ref()
const errorDialogVisible = ref(false)
const isMobile = computed(() => window.innerWidth <= 768)

const adminLoginForm = ref({
  username: '',
  password: '',
  rememberMe: false,
})

// 已弃用：开发模式变量 - 不再需要
// const isDev = import.meta.env.DEV

const adminLoginRules = {
  username: [
    { required: true, message: '请输入管理员用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

const handleAdminLogin = async () => {
  if (!adminLoginFormRef.value) return

  try {
    await adminLoginFormRef.value.validate()

    const creds = {
      username: adminLoginForm.value.username,
      password: adminLoginForm.value.password,
    }

    // 调用管理员登录API - 新的分离式登录系统
    try {
      const response = await authService.adminLogin(creds)
      const body = response.data as { 
        code?: number; 
        msg?: string; 
        data?: { 
          token?: string; 
          username?: string;
          adminRole?: string;
          adminRoleId?: number;
          id?: number;
        } 
      } | { 
        token?: string; 
        username?: string;
        adminRole?: string;
        adminRoleId?: number;
        id?: number;
      }
      
      // 兼容新老返回结构
      const isWrapped = (body as { code?: number }).code !== undefined
      const wrapped = body as { 
        code: number; 
        msg?: string; 
        data?: { 
          token?: string; 
          username?: string;
          adminRole?: string;
          adminRoleId?: number;
          id?: number;
        } 
      }
      const plain = body as { 
        token?: string; 
        username?: string;
        adminRole?: string;
        adminRoleId?: number;
        id?: number;
      }
      
      const ok = (isWrapped && wrapped.code === 200 && wrapped.data) || (!isWrapped && (plain.token || plain.username))
      if (!ok) throw new Error((isWrapped ? wrapped.msg : undefined) || '用户名或密码错误')

      const adminData = isWrapped ? wrapped.data! : plain
      const token = adminData.token
      
      // 构建完整的管理员信息
      const adminInfo = {
        id: adminData.id,
        username: adminData.username || adminLoginForm.value.username,
        adminRole: adminData.adminRole || 'ADMIN',
        adminRoleId: adminData.adminRoleId || 2
      }

      // 写入管理员会话
      authStore.setAdminAuth(adminInfo, token)

      ElMessage.success('管理员登录成功！')
      router.push('/admin')
      return
    } catch (error: unknown) {
      console.error('管理员登录失败:', error)
      // 使用统一的错误处理工具提取错误消息
      const errorMessage = extractErrorMessage(error, '登录失败')
      
      ElMessage.error(`管理员登录失败: ${errorMessage}`)
      // 确保不会有意外的重定向
      return
    }

    // 旧的调用方式已弃用
    // const result = await authStore.loginAdmin(creds)

    // 新的登录逻辑已在上面处理，这里不需要额外的判断
    // if (result.success) {
    //   ElMessage.success('管理员登录成功！')
    //   // 跳转到管理后台
    //   router.push('/admin')
    // } else {
    //   errorDialogVisible.value = true
    // }
  } catch (error) {
    console.error('Admin login validation error:', error)
  }
}

// 已弃用：一键管理员登录功能
// const fillAdminAndLogin = async () => {
//   adminLoginForm.value.username = 'admin'
//   adminLoginForm.value.password = 'admin123'
//   await handleAdminLogin()
// }

const goToUserLogin = () => {
  router.push('/auth/login')
}

// 监听错误状态
watchEffect(() => {
  if (authStore.error) {
    errorDialogVisible.value = true
  }
})

onMounted(() => {
  // 如果已登录且是管理员，跳转到管理后台
  if (authStore.isLoggedIn && authStore.isAdmin) {
    router.push('/admin')
  }
})
</script>

<style scoped lang="scss">
.admin-login-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);

  .admin-login-form-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 2rem;
    background: white;
    max-width: 500px;

    .admin-login-header {
      text-align: center;
      margin-bottom: 2rem;

      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 1rem;
        color: #2c3e50;
        font-weight: bold;
      }

      h2 {
        color: #2c3e50;
        margin: 0 0 0.5rem 0;
        font-size: 1.8rem;
      }

      .subtitle {
        color: #7f8c8d;
        margin: 0;
        font-size: 1rem;
      }
    }

    .admin-login-form {
      width: 100%;
      max-width: 400px;

      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;

        .user-login-link {
          color: #3498db;
          text-decoration: none;
          font-size: 0.9rem;

          &:hover {
            text-decoration: underline;
          }
        }
      }

      .admin-login-button {
        width: 100%;
        height: 48px;
        font-size: 1.1rem;
        background: #2c3e50;
        border-color: #2c3e50;

        &:hover {
          background: #34495e;
          border-color: #34495e;
        }
      }

      .dev-helper {
        margin-top: 1rem;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 8px;
      }

      .back-to-user {
        margin-top: 2rem;
        text-align: center;

        .el-button {
          color: #7f8c8d;

          &:hover {
            color: #2c3e50;
          }
        }
      }
    }
  }

  .admin-login-image {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .admin-login-bg {
      width: 100%;
      height: 100%;
      background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
      position: relative;

      &::before {
        content: '🔐';
        font-size: 8rem;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0.1;
      }
    }
  }
}

@media (max-width: 768px) {
  .admin-login-container {
    flex-direction: column;

    .admin-login-form-wrapper {
      max-width: 100%;
      padding: 1rem;
    }

    .admin-login-image {
      display: none;
    }
  }
}
</style>
